package com.sxf.controller.blog.admin;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sxf.common.tools.CommonTools;
import com.sxf.common.tools.WPConstants;
import com.sxf.controller.SuperController;
import com.sxf.controller.formbean.PostVO;
import com.sxf.controller.formbean.TermVO;
import com.sxf.controller.formbean.UserVO;
import com.sxf.domain.Post;
import com.sxf.domain.PostMeta;
import com.sxf.domain.TermRelationships;
import com.sxf.formbean.PostForm;
import com.sxf.mybatis.page.Pagination;
import com.sxf.querybean.PostQuery;
import com.sxf.querybean.PostQuery.QueryType;
import com.sxf.querybean.TermQuery;
import com.sxf.querybean.TermRelationshipsQuery;
import com.sxf.service.PostService;
import com.sxf.service.TermRelationshipsService;
import com.sxf.service.TermService;
import com.sxf.service.TermTaxonomyService;
import com.sxf.view.datatables.DataTables;
import com.sxf.view.datatables.DatatablesHelp;

/**
 * @author phsxf01
 * 
 */
@Controller
@RequestMapping("blog/admin/post")
public class PostController extends SuperController {
	@Resource
	private PostService postService;
	@Resource
	private TermService termService;
	@Resource
	private TermRelationshipsService termRelationshipsService;
	@Resource
	private TermTaxonomyService termTaxonomyService;

	// @Value("web_domain")
	// private String webDomain;

	// 数据绑定
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CustomDateEditor dateEditor = new CustomDateEditor(df, true);
		binder.registerCustomEditor(Date.class, dateEditor);
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}

	@RequestMapping(value = "")
	public ModelAndView toPost() throws Exception {
		ModelMap map = new ModelMap();
		List<Date> archiveList = postService.getArchivePost();
		map.put("archiveList", archiveList);
		TermQuery query = new TermQuery();
		query.setTaxonomy(WPConstants.TAXONOMY_POST_CATEGORY);
		List<TermVO> termList = termService.queryList(query);
		map.put("termList", termList);
		return getModelAndView(map, "blog/admin/post");
	}

	/**
	 * @param page
	 *            当前第几页
	 * 
	 * @param rows
	 *            每页显示的记录数
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/listAjax")
	@ResponseBody
	public Pagination<PostVO> listAjax(
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			WebRequest request) throws Exception {
		// ModelMap mm = new ModelMap();
		UserVO user = getCurrentUser();
		if (user != null) {
			PostQuery query = new PostQuery();
			query.queryType = QueryType.queryByTerm;
			if (StringUtils.isNotBlank(page)) {
				try {
					query.setCurrentPage(Integer.parseInt(page));
				} catch (Exception e) {
				}
			}
			if (StringUtils.isNotBlank(rows)) {
				try {
					query.setPageSize(Integer.parseInt(rows));
				} catch (Exception e) {
				}
			}
			String status = request.getParameter("status");
			if (StringUtils.isNotBlank(status)) {
				query.setStatus(status);
			}
			String dateByMonth = request.getParameter("dateByMonth");
			if (StringUtils.isNotBlank(dateByMonth)) {
				query.setDateByMonth(dateByMonth);
			}
			String postCategory = request.getParameter("postCategory");
			if (StringUtils.isNotBlank(postCategory)) {
				query.setTermId(Long.valueOf(postCategory));
			}
			String title = request.getParameter("title");
			if (StringUtils.isNotBlank(title)) {
				query.setTitle(title);
			}
			String dtjson = request.getParameter("dtjson");
			if (StringUtils.isNotBlank(dtjson)) {
				DataTables dt = DatatablesHelp.getDataTable(dtjson);
				String name = dt.getSearch();
				if (StringUtils.isNotBlank(name)) {
					query.setTitle(name);
				}
			}
			if (StringUtils.isBlank(query.getStatus())) {
				List<String> statusList = new ArrayList<String>();
				statusList.add(WPConstants.POST_STATUS_PUBLISH);
				statusList.add(WPConstants.POST_STATUS_DRAFT);
				statusList.add(WPConstants.POST_STATUS_PENDING);
				query.setStatusList(statusList);
			}

			query.setAuthor(user.getId());
			query.setQueryAllColumn(false);
			Pagination<PostVO> pages = postService.queryPage(query);
			// mm.put("page", page);
			return pages;
		}

		return null;
	}

	@RequestMapping("/statisticsAjax")
	@ResponseBody
	public Map<String, Integer> statisticsAjax() throws Exception {
		Map<String, Integer> map = postService.queryStatistic();
		return map;
	}

	/**
	 * @param postId
	 *            文章编号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	public ModelAndView toAddOrUpdate(
			@RequestParam(value = "postId", required = false) Long postId)
			throws Exception {
		ModelAndView mav = new ModelAndView("blog/admin/post_edit");
		mav.addObject("user", getCurrentUser());
		if (postId != null) {
			PostQuery pq = new PostQuery();
			pq.setId(postId);
			pq.setQueryAllColumn(true);
			PostVO post = postService.queryOne(pq);
			if (post != null) {
				mav.addObject("post", post);
			}
		}

		TermQuery query = new TermQuery();
		query.setTaxonomy(WPConstants.TAXONOMY_POST_CATEGORY);
		List<TermVO> termList = termService.queryList(query);
		mav.addObject("termList", termList);
		return mav;
	}

	@RequestMapping("/doAddOrUpdate")
	public ModelAndView doAddOrUpdate(@Valid @ModelAttribute PostForm pF,
			BindingResult br, HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		if (br.hasErrors()) {
			if (pF.getId() != null) {

			}
		}
		if (pF != null) {
			Post post = new Post();
			BeanUtils.copyProperties(pF, post);
			int i = 0;
			if (post.getId() != null) {
				Date d = new Date();
				post.setModified(d);
				post.setModifiedGmt(CommonTools.getGMT0(d));
				i = postService.update(post);// 更新
			} else if (StringUtils.isNotBlank(pF.getTitle())) {
				post.setPassword("");
				post.setMenuOrder(0);
				post.setCommentCount(0l);
				post.setPinged("");
				post.setContentFiltered("");
				if ("public".equals(pF.getVisibility())) {
					if (!WPConstants.POST_STATUS_PUBLISH.equals(pF.getStatus())) {
						post.setStatus(WPConstants.POST_STATUS_PUBLISH);
					}

					// 是否置顶
					if ("sticky".equals(pF.getSticky())) {

					}
				} else if ("password".equals(pF.getVisibility())) {
					post.setPassword(pF.getPassword());
					post.setStatus("password");
				} else if ("private".equals(pF.getVisibility())) {
					post.setStatus("private");
				}

				if (pF.getDate() == null) {
					post.setDate(new Date());
				}
				post.setDateGmt(CommonTools.getGMT0(post.getDate()));

				post.setModified(post.getDate());
				post.setModifiedGmt(CommonTools.getGMT0(post.getDate()));
				i = postService.insert(post);// 插入

				if (post.getId() != null) {
					Post updatePost = new Post();
					updatePost.setId(post.getId());
					StringBuilder sb = new StringBuilder();
					sb.append("http://");
					sb.append(request.getLocalAddr());
					if (request.getLocalPort() != 80) {
						sb.append(":");
						sb.append(request.getLocalPort());
					}
					sb.append("/?p=");
					sb.append(post.getId());
					updatePost.setGuid(sb.toString());
					postService.update(updatePost);
				}
			}

			if (i > 0) {
				Long postId = post.getId();
				// 删除原来post对应的分类和标签
				deleteTermByPostId(postId);
				// 添加category
				String[] categoryArr = request.getParameterValues("categorys");
				if (categoryArr != null && categoryArr.length > 0) {
					for (String category : categoryArr) {
						TermRelationshipsQuery trsq = new TermRelationshipsQuery();
						trsq.setObjectId(postId);
						trsq.setTermTaxonomyId(Long.valueOf(category));
						if (termRelationshipsService.queryOne(trsq) == null) {
							TermRelationships trs = new TermRelationships();
							trs.setObjectId(postId);
							trs.setTermTaxonomyId(Long.valueOf(category));
							trs.setTermOrder(0);
							termRelationshipsService.insert(trs);
						}
					}
				}
				// 添加tag
				String[] tagsArr = request.getParameterValues("tags");
				if (tagsArr != null && tagsArr.length > 0) {
					for (String tag : tagsArr) {
						TermRelationshipsQuery trsq = new TermRelationshipsQuery();
						trsq.setObjectId(postId);
						trsq.setTermTaxonomyId(Long.valueOf(tag));
						if (termRelationshipsService.queryOne(trsq) == null) {
							TermRelationships trs = new TermRelationships();
							trs.setObjectId(postId);
							trs.setTermTaxonomyId(Long.valueOf(tag));
							trs.setTermOrder(0);
							termRelationshipsService.insert(trs);
						}

					}
				}
				mav.setViewName("forward:/blog/admin/post/edit?postId="
						+ post.getId());
			}
		}

		return mav;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String delete(@RequestParam(required = true) Long postId,
			WebRequest request) throws Exception {
		if (postId != null) {
			Post post = new Post();
			post.setId(postId);
			postService.delete(post);
			PostMeta pm = new PostMeta();
			pm.setPostId(postId);
			postService.deletePostMeta(pm);
			// 删除原来post对应的分类和标签
			deleteTermByPostId(postId);
		}
		return "success";
	}

	private boolean deleteTermByPostId(Long postId) {
		boolean flag = true;
		TermQuery termQuery = new TermQuery();
		List<String> taxonomyList = new ArrayList<String>();
		taxonomyList.add(WPConstants.TAXONOMY_POST_CATEGORY);
		taxonomyList.add(WPConstants.TAXONOMY_POST_TAG);
		termQuery.setTaxonomyList(taxonomyList);
		List<TermVO> termVOList = termService.queryList(termQuery);
		if (termVOList != null && !termVOList.isEmpty()) {
			TermRelationships trs = new TermRelationships();
			trs.setObjectId(postId);
			for (TermVO tv : termVOList) {
				trs.setTermTaxonomyId(tv.getTaxonomyId());
				termRelationshipsService.delete(trs);
			}
		}
		return flag;
	}
}
